﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public abstract class UISwitchBase : MonoBehaviour
{
    [Tooltip("应用的父对象, 默认为自身")]
    public Transform parent = null;
    public enum MODE
    {
        SELECT_ONE,
        DISPLAY_COUNT,
        HIDE_COUNT,
    }


    [Tooltip("比较模式,SELECT_ONE = 显示等于index 的子节点,\n DISPLAY_COUNT = 显示指定数量的子节点,\n HIDE_COUNT = 隐藏指定数量的子节点")]
    public MODE mode = MODE.SELECT_ONE;

    private void Awake()
    {
        if (parent == null) parent = transform;
    }

    [SerializeField]
    private int _index;
    public int index
    {
        get
        {
            return _index;
        }
        set
        {
            var max = (mode != MODE.SELECT_ONE) ? parent.childCount : (parent.childCount - 1);
            if (value > max) value = max;
            if (value < 0) value = 0;
            UpdateFromIndex(value);
            _index = value;
        }
    }

    [Tooltip("是否翻转序号,适合反向改变子节点的状态,比如格斗游戏中左右两边方向不同的条")]
    public bool isReverse = false;

#if UNITY_EDITOR
    bool _dirty = false;
    private void OnValidate()
    {
        if (parent == null) parent = transform;
        var max = (mode != MODE.SELECT_ONE) ? parent.childCount : (parent.childCount - 1);
        if (_index > max) _index = max;
        if (_index < 0) _index = 0;
        _dirty = true;
    }

    private void Update()
    {
        if (_dirty)
        {
            _dirty = false;
            UpdateFromIndex(_index);
        }
    }

#endif

    public int GetMaxIndex()
    {
        return this.parent.childCount;
    }

    public abstract void UpdateChild(Transform child, bool state);

    protected void UpdateFromIndex(int value)
    {

        for (int i = 0; i < this.parent.childCount; i++)
        {
            bool res = false;
            var child = this.parent.GetChild(isReverse ? (this.parent.childCount - 1 - i) : i);
            switch (mode)
            {

                case MODE.SELECT_ONE:
                    res = i == value ? true : false;
                    break;
                case MODE.HIDE_COUNT:
                    res = i >= value ? true : false;

                    break;
                case MODE.DISPLAY_COUNT:
                    res = i < value ? true : false;
                    break;
                default:
                    break;
            }

            this.UpdateChild(child, res);

        }


    }
}
